﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Service
{


    /// <summary>
    /// 需要调度任务的基类
    /// </summary>
    public abstract class BaseTimedTask : BaseJob, ITimedTaskControl
    {

        /// <summary>
        /// 任务的名称
        /// </summary>
        /// <param name="taskName"></param>
        public BaseTimedTask(string taskName)
        {
            if (string.IsNullOrWhiteSpace(taskName))
            {
                throw new Exception("The task name can't be null or empty.");
            }
            this.TaskName = taskName;
        }


        /// <summary>
        /// 任务的名称
        /// </summary>
        public string TaskName { get; private set; }


        /// <summary>
        /// 任务是否在执行
        /// </summary>
        public bool Running { get; protected set; }


        /// <summary>
        /// 任务初始化
        /// </summary>
        /// <returns></returns>
        public virtual Result Initialize()
        {
            return new Result();
        }


        /// <summary>
        /// 任务自动运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public Result AutoRun(string param)
        {
            Result result = new Result();
            if (!this.Running)
            {
                this.Running = true;
                try
                {
                    //检查任务结果
                    result.ReceiveResult(this.Run(param));
                    return result;
                }
                catch (Exception exception)
                {
                    result.AddError(exception, null);
                    return result;
                }
                finally
                {
                    this.Running = false;
                }
            }
            result.AddError("The current timed task instance is already running.", null);
            return result;
        }


        /// <summary>
        /// 具体任务需要执行的逻辑
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public abstract Result Run(string param);



    }
}
